import Vue from 'vue'
import * as time from '@/utils/time'
import * as number from '@/utils/number'
import { applyCurrencyPriceWithState } from '@/utils/market'

// 涨跌幅计算
function fluctuation (data) {
  if (!data) { return 0 }
  const { last, open } = data
  const rate = ((last - open) / open) * 100
  const formatRate = number.format(rate, 2)
  return rate < 0 ? `${formatRate}%` : `+${formatRate}%`
}

function formatSize (size) {
  if (!size) { return 0.0 }
  const num = 1000
  if (size < num) { return number.format(size) }
  if (size < num ** 2) { return number.format(size / num) + 'k' } // kb
  if (size < num ** 3) { return number.format(size / num ** 2) + 'm' } // M
  if (size < num ** 4) { return number.format(size / num ** 3) + 'g' } // G
  return number.format(size / num ** 4) + 't' // T
}

function toLowerCase (str) {
  return str.toLowerCase()
}

function createFilterRegister (Vue) {
  return (name, fn) => {
    Vue.filter(name, fn)
  }
}

export default function ({ store: { state } }) {
  const currencyPrice = applyCurrencyPriceWithState(state)
  const allFilters = {
    fluctuation,
    formatSize,
    numberFormat: number.format,
    priceFormat: number.priceFormat,
    currency: number.currency,
    toLowerCase,
    currencyPrice,
    timeFormat: time.format
  }
  const filterRegister = createFilterRegister(Vue)
  Object.keys(allFilters).forEach((name) => {
    filterRegister(name, allFilters[name])
  })
}
